﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using OperationPlugins.Mvc.Filters;
using System.Web.Mvc;
using TimeProject.Engine;
using TimeProject.Engine.DbContent;
using TimeProject.Engine.DbModels;
using TimeProject.Engine.Providers;
using TimeProject.WebSite.ViewModels;


namespace TimeProject.WebSite.Controllers
{
    public partial class TimeProjectController
    {
        [HttpGet]
        [CurrentOperation(TimeProjectOperations.MyOrganizations)]
        public ActionResult MyOrganizations()
        {
            MyOrganizationsViewModel vm = new MyOrganizationsViewModel();
            LoadMyOrganizations(vm);
            return View(vm);
        }

        private void LoadMyOrganizations(MyOrganizationsViewModel vm)
        {
            OrganizationUser[] organizationUsers = Db.GetOrganizationUsersByUser(UserId).Where(x => x.Status != OrganizationUserStatus.Rejected)
                                                                                        .ToArray();

            foreach (OrganizationUser organizationUser in organizationUsers)
            {
                for (int i = 0; i < 3; i++)
                {
                    MyOrganizationViewModel ovm = new MyOrganizationViewModel();

                    ovm.PublicId = EntityPublicIdProvider.GetPublicId(organizationUser.Organization);
                    ovm.Code = organizationUser.Organization.Code;
                    ovm.FullName = organizationUser.Organization.FullName;
                    ovm.Description = organizationUser.Organization.Description;
                    ovm.MyRole = organizationUser.Role.ToString();

                    if (organizationUser.Role == OrganizationUserRole.Manager &&
                        organizationUser.Status == OrganizationUserStatus.Valid)
                    {
                        ovm.IsManageAllowed = true;
                        ovm.IsDeleteAllowed = true;
                    }

                    ovm.IsRemoveMembershipAllowed = true;

                    vm.Organizations.Add(ovm);
                }
            }

            if (vm.Organizations.Any())
            {
                MyOrganizationViewModel selected = vm.Organizations.First();
                LoadOrganization(vm, selected);
                vm.SetAsSelected(selected);
            }
            
        }

        [HttpPost]
        [CurrentOperation(TimeProjectOperations.UndoMyOrganizationsChanges)]
        public ActionResult UndoMyOrganizationsChanges(MyOrganizationsViewModel vm)
        {
            return Json(vm, () =>
            {
                vm.Initialize();
                LoadMyOrganizations(vm);
            });
        }


        [HttpPost]
        [CurrentOperation(TimeProjectOperations.JoinOrganization)]
        public ActionResult JoinOrganization(MyOrganizationsViewModel vm)
        {
            return Json(vm, () =>
            {
            });
        }

        [HttpPost]
        [CurrentOperation(TimeProjectOperations.CreateNewOrganization)]
        public ActionResult CreateNewOrganization(MyOrganizationsViewModel vm)
        {
            return Json(vm, () =>
            {
                vm.CreateNewOrganization();
            });
        }

        [HttpPost]
        [CurrentOperation(TimeProjectOperations.DeleteOrganization)]
        public ActionResult DeleteOrganization(MyOrganizationsViewModel vm, int index)
        {
            return Json(vm, () =>
            {
                MyOrganizationViewModel selected = vm.Organizations[index];
                vm.DeleteOrganization(selected);
            });
        }

        [HttpPost]
        [CurrentOperation(TimeProjectOperations.RemoveOrganizationMembership)]
        public ActionResult RemoveOrganizationMembership(MyOrganizationsViewModel vm, int index)
        {
            return Json(vm, () =>
            {
            });
        }

        [HttpPost]
        //[DisablePluginsValidation]
        [CurrentOperation(TimeProjectOperations.ShowOrganization)]
        public ActionResult ShowOrganization(MyOrganizationsViewModel vm, int index)
        {
            return Json(vm, () =>
            {
                MyOrganizationViewModel selected = vm.Organizations[index];

                if (selected.IsFullyLoaded == false && selected.IsManageAllowed)
                {
                    LoadOrganization(vm, selected);
                }

                vm.SetAsSelected(selected);
            });
        }

        private void LoadOrganization(MyOrganizationsViewModel vm, MyOrganizationViewModel selected)
        {
            int organizationId;
            if (EntityPublicIdProvider.TryParseEntityId(selected.PublicId, out organizationId) == false)
            {
                throw new InvalidOperationException();
            }

            OrganizationUser[] organizationUsers =
                Db.GetOrganizationUsersByOrganization(organizationId)
                    .Where(x => x.Status != OrganizationUserStatus.Rejected)
                    .ToArray();

            bool manager = organizationUsers.Any(x => x.UserId == UserId &&
                                                      x.Role == OrganizationUserRole.Manager &&
                                                      x.Status == OrganizationUserStatus.Valid);

            if (manager == false)
            {
                throw new InvalidOperationException();
            }

            foreach (OrganizationUser organizationUser in organizationUsers)
            {
                var member = new MyOrganizationMemberViewModel();
                member.PublicId = EntityPublicIdProvider.GetPublicId(organizationUser.User);
                member.FullName = organizationUser.User.FullName;
                member.Role = organizationUser.Role.ToString();
                member.Status = organizationUser.Status.ToString();

                if (organizationUser.Status == OrganizationUserStatus.Pending)
                {
                    member.IsAcceptRequestAllowed = true;
                    member.IsCancelRequestAllowed = true;
                }

                if (organizationUser.Role == OrganizationUserRole.Contributor &&
                    organizationUser.Status == OrganizationUserStatus.Valid)
                {
                    member.IsPromoteToManagerAllowed = true;
                }

                if (organizationUser.Status == OrganizationUserStatus.Valid)
                {
                    member.IsRemoveMembershipAllowed = true;
                }

                selected.Members.Add(member);
            }

            selected.IsFullyLoaded = true;
        }

    }
}